package activity.setting;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import com.hichip.base.HiLog;
import com.hichip.callback.ICameraIOSessionCallback;
import com.hichip.campro.R;
import com.hichip.content.HiChipDefines;
import com.hichip.control.HiCamera;
import com.hichip.data.HiDeviceInfo;
import com.hichip.tools.Packet;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import base.HiActivity;
import bean.MyCamera;
import butterknife.BindView;
import common.CamHiDefines;
import common.HiDataValue;
import common.TitleView;
import main.MainActivity;
import utils.HiToast;

/**
 * 设备信息
 */
public class DeviceInfoActivity extends HiActivity implements ICameraIOSessionCallback {
    private MyCamera mCamera;
    private HiChipDefines.HI_P2P_GET_DEV_INFO_EXT deviceInfo;
    private TextView mTvdeviceType;
    private TextView device_name_tv, network_state_tv, user_connections_tv, software_version_tv, ip_address_tv, subnet_mask_tv, gateway_tv, dns_tv;
    @BindView(R.id.tv_upgrade_online_settings) TextView tv_upgrade_online_settings;
    private static final int UPDATA_STATE_NONE = 0;
    private static final int UPDATA_STATE_CHECKING = 1;
    private static final int GET_UPDATE_VERSION_NUM = 0X9999;
    private static final int GET_UPDATE_VERSION_DATA = 0X10000;

    private int updateStatus = UPDATA_STATE_NONE;
    private boolean send = false;
    boolean isUpdate = false;
    private String redirectAddr = null;
    private static long updateTime = 0;


    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        String uid = getIntent().getStringExtra(HiDataValue.EXTRAS_KEY_UID);
        for (MyCamera camera : HiDataValue.CameraList) {
            if (uid.equals(camera.getUid())) {
                mCamera = camera;
                if (mCamera.getConnectState() == HiCamera.CAMERA_CONNECTION_STATE_LOGIN) {
                    mCamera.sendIOCtrl(HiChipDefines.HI_P2P_GET_NET_PARAM, new byte[0]);
                }
                break;
            }
        }
        showjuHuaDialog();
        initView();
        handIsSup_DEV_INFO_EXT();

    }

    @Override
    protected int setLayoutId() {
        return R.layout.activity_device_info;
    }


    private void handIsSup_DEV_INFO_EXT() {
        if (mCamera.getCommandFunction(HiChipDefines.HI_P2P_GET_DEV_INFO_EXT)) {
            mCamera.sendIOCtrl(HiChipDefines.HI_P2P_GET_DEV_INFO_EXT, new byte[0]);
        } else {
            mCamera.sendIOCtrl(HiChipDefines.HI_P2P_GET_DEV_INFO, new byte[0]);
            mCamera.sendIOCtrl(HiChipDefines.HI_P2P_GET_VENDOR_INFO, new byte[0]);
        }
    }

    private void initView() {
        TitleView title = (TitleView) findViewById(R.id.title_top);
        title.setTitle(getResources().getString(R.string.title_equipment_information));
        title.setButton(TitleView.NAVIGATION_BUTTON_LEFT);
        title.setNavigationBarButtonListener(new TitleView.NavigationBarButtonListener() {

            @Override
            public void OnNavigationButtonClick(int which) {
                switch (which) {
                    case TitleView.NAVIGATION_BUTTON_LEFT:
                        DeviceInfoActivity.this.finish();
                        break;
                }
            }
        });

        device_name_tv = (TextView) findViewById(R.id.device_name_tv);
        network_state_tv = (TextView) findViewById(R.id.network_state_tv);
        user_connections_tv = (TextView) findViewById(R.id.user_connections_tv);
        software_version_tv = (TextView) findViewById(R.id.software_version_tv);
        mTvdeviceType = (TextView) findViewById(R.id.device_type);

        ip_address_tv = (TextView) findViewById(R.id.ip_address_tv);
        subnet_mask_tv = (TextView) findViewById(R.id.subnet_mask_tv);
        gateway_tv = (TextView) findViewById(R.id.gateway_tv);
        dns_tv = (TextView) findViewById(R.id.dns_tv);

    }

    @Override
    public void receiveIOCtrlData(HiCamera arg0, int arg1, byte[] arg2, int arg3) {
        if (arg0 != mCamera) return;
        Bundle bundle = new Bundle();
        bundle.putByteArray(HiDataValue.EXTRAS_KEY_DATA, arg2);
        Message msg = handler.obtainMessage();
        msg.what = HiDataValue.HANDLE_MESSAGE_RECEIVE_IOCTRL;
        msg.obj = arg0;
        msg.arg1 = arg1;
        msg.arg2 = arg3;
        msg.setData(bundle);
        handler.sendMessage(msg);

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HiDataValue.HANDLE_MESSAGE_SESSION_STATE:
                    handSession(msg);
                    break;
//                case HiChipDefines.HI_P2P_SET_DOWNLOAD:
//                    Log.i("tedy","--我更改为333了--");
//                    mCamera.isSystemState = 3;
//                    break;
                case GET_UPDATE_VERSION_NUM:
                    if (msg.arg1 == 1) {
                        updateInfo = (UpdateInfo) msg.obj;
                        send = true;
                        if (mCamera != null) {
                            mCamera.registerIOSessionListener(DeviceInfoActivity.this);
                        }
                        handleDeviceInfo();
                    } else {
                        updateStatus = UPDATA_STATE_NONE;
                        HiToast.showToast(DeviceInfoActivity.this, getString(R.string.tips_update_system_failed));
                        dismissProgressDialog();
                    }
                    break;
                case GET_UPDATE_VERSION_DATA:
                    updateStatus = UPDATA_STATE_NONE;
                    showDialogOld();
                    break;
                case HiDataValue.HANDLE_MESSAGE_RECEIVE_IOCTRL:
                    if (msg.arg2 == 0) {
                        Bundle bundle = msg.getData();
                        byte[] data = bundle.getByteArray(HiDataValue.EXTRAS_KEY_DATA);
                        switch (msg.arg1) {
                            case HiChipDefines.HI_P2P_SET_DOWNLOAD:
                                Log.i("tedy", "--我更改为333了--");
                                mCamera.isSystemState = 3;
                                break;
                            case HiChipDefines.HI_P2P_GET_VENDOR_INFO:
                                dismissjuHuaDialog();
                                HiChipDefines.HI_P2P_S_VENDOR vendor = new HiChipDefines.HI_P2P_S_VENDOR(data);
                                mTvdeviceType.setText(new String(vendor.strProduct).trim());
                                break;
                            case HiChipDefines.HI_P2P_GET_DEV_INFO_EXT:
                                dismissjuHuaDialog();
                                deviceInfo = new HiChipDefines.HI_P2P_GET_DEV_INFO_EXT(data);
                                device_name_tv.setText(Packet.getString(deviceInfo.aszSystemName));
                                String state[] = getResources().getStringArray(R.array.net_work_style);
                                network_state_tv.setText(state[deviceInfo.u32NetType]);
                                user_connections_tv.setText(deviceInfo.sUserNum + "");
                                mTvdeviceType.setText(Packet.getString(deviceInfo.aszSystemModel));
                                software_version_tv.setText(Packet.getString(deviceInfo.aszSystemSoftVersion));
                                String version = Packet.getString(deviceInfo.aszSystemSoftVersion);
                                if (!TextUtils.isEmpty(version)) {
                                    handVerionAndView(version);
                                }
                                break;
                            case HiChipDefines.HI_P2P_GET_DEV_INFO:
                                dismissjuHuaDialog();
                                HiChipDefines.HI_P2P_S_DEV_INFO info = new HiChipDefines.HI_P2P_S_DEV_INFO(data);
                                String[] arr = getResources().getStringArray(R.array.net_work_style);
                                network_state_tv.setText(arr[info.u32NetType]);
                                user_connections_tv.setText(info.sUserNum + "");
                                software_version_tv.setText(Packet.getString(info.strSoftVer));
                                version = Packet.getString(info.strSoftVer);
                                if (!TextUtils.isEmpty(version)) {
                                    handVerionAndView(version);
                                }
                                break;
                            case HiChipDefines.HI_P2P_GET_NET_PARAM:
                                dismissjuHuaDialog();
                                HiChipDefines.HI_P2P_S_NET_PARAM net_param = new HiChipDefines.HI_P2P_S_NET_PARAM(data);
                                String ip = Packet.getString(net_param.strIPAddr);
                                String mask = Packet.getString(net_param.strNetMask);
                                String getway = Packet.getString(net_param.strGateWay);
                                String dns = Packet.getString(net_param.strFDNSIP);
                                ip_address_tv.setText(ip);
                                subnet_mask_tv.setText(mask);
                                gateway_tv.setText(getway);
                                dns_tv.setText(dns);
                                break;
                            case CamHiDefines.HI_P2P_ALARM_ADDRESS_GET:
                                dismissjuHuaDialog();
                                CamHiDefines.HI_P2P_ALARM_ADDRESS aa = new CamHiDefines.HI_P2P_ALARM_ADDRESS(data);
                                HiLog.e(Packet.getString(aa.szAlarmAddr));
                                break;

                        }
                    } else {
                        switch (msg.arg1) {
                            case HiChipDefines.HI_P2P_SET_DOWNLOAD:
                                dismissjuHuaDialog();
                                mCamera.isSystemState = 3;
                                break;
                        }

                    }
                    break;

            }
        }
    };

    private void handSession(Message msg) {
        switch (msg.arg1) {
            case HiCamera.CAMERA_CONNECTION_STATE_LOGIN:
                mCamera.setReconnectTimes(10);
                dismissjuHuaDialog();
                mCamera.isSystemState = 0;
                Intent intent = new Intent(DeviceInfoActivity.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void receiveSessionState(HiCamera arg0, int arg1) {
        if (arg0 != mCamera) {
            return;
        }
        Message message = Message.obtain();
        message.what = HiDataValue.HANDLE_MESSAGE_SESSION_STATE;
        message.arg1 = arg1;
        handler.sendMessage(message);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mCamera != null) {
            mCamera.registerIOSessionListener(this);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mCamera != null) {
            mCamera.unregisterIOSessionListener(this);
        }
    }

    // string=V11.1.8.1.4-20170707
    private void handVerionAndView(String string) {
        String[] strings = string.split("\\.");
        if (strings.length >= 2) {
            if (mCamera.getChipVersion() == HiDeviceInfo.CHIP_VERSION_GOKE) {
                tv_upgrade_online_settings.setVisibility(View.VISIBLE);
            } else if (mCamera.getChipVersion() == HiDeviceInfo.CHIP_VERSION_HISI && strings[0].equals("V11") && strings[1].equals("1") && strings[2].equals("8")) {
                tv_upgrade_online_settings.setVisibility(View.VISIBLE);
            } else {
                tv_upgrade_online_settings.setVisibility(View.GONE);
            }
            tv_upgrade_online_settings.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (updateStatus == UPDATA_STATE_NONE) {
                        showProgressDialog();
                        checkUpdate();
                    }

                }
            });
        }
    }

    private ProgressDialog progressDialog;

    private void showProgressDialog() {
        progressDialog = new ProgressDialog(DeviceInfoActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setCancelable(true);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setIcon(R.mipmap.ic_launcher);
        progressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
            }
        });
        progressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                return false;
            }
        });
        progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
            }
        });
        progressDialog.setMessage(getText(R.string.tips_loading));
        progressDialog.show();
    }

    private void checkUpdate() {

        new ThreadHttpResqust().start();

        updateStatus = UPDATA_STATE_CHECKING;
    }


    private static String downloadUrl = "http://47.91.141.20/goke_update.html";// 锟斤拷锟斤拷锟斤拷锟斤拷址
    private UpdateInfo updateInfo;

    private class UpdateInfo {
        String url;
        String ver;

        public UpdateInfo(String u, String v) {
            url = u;
            ver = v;
        }
    }

    private List<UpdateInfo> mListUpdataInfo = new ArrayList<UpdateInfo>();


    private class ThreadHttpResqust extends Thread {
        public ThreadHttpResqust() {
        }

        public void run() {
            String url = downloadUrl;
            HttpResponse httpResponse = null;
            try {
                HttpGet httpGet = new HttpGet(url);
                httpResponse = new DefaultHttpClient().execute(httpGet);
                if (httpResponse.getStatusLine().getStatusCode() == 200) {
                    String result = EntityUtils.toString(httpResponse.getEntity());
                    HiLog.v("result:" + result);
                    try {
                        JSONObject resultJson = new JSONObject(result);
                        JSONArray listArray = resultJson.getJSONArray("list");
                        for (int i = 0; i < listArray.length(); i++) {
                            JSONObject jsonObj = listArray.getJSONObject(i);
                            String u = jsonObj.getString("url");
                            String v = jsonObj.getString("ver");
                            UpdateInfo updateInfo = new UpdateInfo(u, v);
                            mListUpdataInfo.add(updateInfo);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (mListUpdataInfo.size() > 0) {
                        Message msg = new Message();
                        msg.what = GET_UPDATE_VERSION_NUM;
                        msg.arg1 = 1;
                        handler.sendMessage(msg);
                        return;
                    }
                }
                Message msg = new Message();
                msg.what = GET_UPDATE_VERSION_NUM;
                msg.arg1 = 0;
                handler.sendMessage(msg);
            } catch (Exception e) {
                Message msg = new Message();
                msg.what = GET_UPDATE_VERSION_NUM;
                msg.arg1 = 0;
                handler.sendMessage(msg);
            }
        }
    }

    private static String getString(byte[] data) {

        StringBuilder sBuilder = new StringBuilder();

        for (int i = 0; i < data.length; i++) {

            if (data[i] == 0x0) break;

            sBuilder.append((char) data[i]);
        }

        return sBuilder.toString();
    }

    private void handleDeviceInfo() {
        String version = getString(mCamera.getDeciveInfo().aszSystemSoftVersion);
        for (UpdateInfo upinfo : mListUpdataInfo) {
            HiLog.v("version:" + version);
            String[] b_new = upinfo.ver.split("\\.");
            String[] b_old = version.split("\\.");
            if ((b_new.length == b_old.length) && b_old.length == 5) {
                for (int i = 0; i < b_new.length; i++) {
                    if (i == b_new.length - 1) {
                        String[] last_new_array = b_new[i].split("-");
                        String[] last_old_array = b_old[i].split("-");
                        HiLog.v("last_new_array:" + last_new_array.length + "  last_old_array:" + last_old_array.length);
                        int newi = 0;
                        if (last_new_array.length >= 1) {
                            newi = Integer.parseInt(last_new_array[0]);
                        }
                        int oldi = 0;
                        if (last_old_array.length >= 1) {
                            oldi = Integer.parseInt(last_old_array[0]);
                        }
                        //111
                        if (newi > oldi) {
                            updateInfo = upinfo;
                            isUpdate = true;
                        }
                    } else {
                        if (!b_old[i].equals(b_new[i])) {
                            isUpdate = false;
                            break;
                        }
                    }
                }
            }
            if (isUpdate) {
                break;
            }
        }
        if (isUpdate) {
            if (updateInfo == null) return;
            redirectAddr = updateInfo.url + updateInfo.ver + ".exe";
            ThreadCheckRedirect tr = new ThreadCheckRedirect();
            tr.start();
        } else {
            showDialogNew();
            updateStatus = UPDATA_STATE_NONE;
        }
    }


    private class ThreadCheckRedirect extends Thread {
        public void run() {

            Socket socket = null;
            try {
                // InetAddress address = new InetAddress();
                // InetAddress addr = InetAddress.getByName("www.baidu.com");

                // socket = new Socket(addr,80);

                if (updateInfo == null) {

                }

                System.out.println("updateInfo:" + updateInfo);
                System.out.println("updateInfo.url:" + updateInfo.url);

                String host = null;
                int port = 80;
                socket = new Socket(); // 姝ゆ椂Socket瀵硅薄鏈粦瀹氭湰鍦扮鍙�,骞朵笖鏈繛鎺ヨ繙绋嬫湇鍔″櫒
                socket.setReuseAddress(true);

                // Pattern p = Pattern.compile("(?<=//|)((\\w)+\\.)+\\w+");
                // Matcher matcher = p.matcher(updateInfo.url);
                // if (matcher.find()) {
                // host = matcher.group();
                // System.out.println("host:"+host);
                // }
                //

                String host_temp = null;
                Pattern p2 = Pattern.compile("(?<=//|)((\\w)+\\.)+\\w+(:\\d{0,5})?");
                Matcher matcher2 = p2.matcher(updateInfo.url);
                if (matcher2.find()) {
                    host_temp = matcher2.group();
                    System.out.println("host2:" + host_temp);
                }

                // if(host_temp == null)
                // return;

                // 濡傛灉
                if (host_temp.contains(":") == false) {
                    host = host_temp;
                } else {

                    String[] ipPortArr = host_temp.split(":");
                    host = ipPortArr[0];

                    port = Integer.parseInt(ipPortArr[1]);
                    System.out.println("---00port:      " + ipPortArr[0]);
                    System.out.println("---port:    " + port);
                }

                SocketAddress remoteAddr = new InetSocketAddress(host, port);
                socket.connect(remoteAddr);

                DataOutputStream doc = new DataOutputStream(socket.getOutputStream());
                String sendhead = "GET /" + updateInfo.ver + ".exe HTTP/1.1\r\n";
                sendhead += "Accept: */*\r\n";
                sendhead += "Accept-Language: zh-cn\r\n";
                sendhead += "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)\r\n";
                sendhead += "Host: " + host + "\r\n";
                sendhead += "Connection: Keep-Alive\r\n";
                sendhead += "\r\n";

                System.out.println("sendhead:" + sendhead);
                doc.write(sendhead.getBytes());

                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                while (true) {
                    String str = in.readLine();
                    System.out.println("in.readLine:" + str);

                    if (str.contains("HTTP/")) {
                        // if (str.contains("200 OK")) {
                        // break;
                        // }
                        if (str.contains("302") || str.contains("301")) {
                            System.out.println("------------ 301 302 Found----------------");
                        } else {
                            break;
                        }
                    }
                    if (str.contains("Location:")) {
                        String newhttp = str.substring(9).trim();
                        System.out.println("1------------ newhttp----------------:" + newhttp);
                        redirectAddr = str.substring(9).trim();
                        break;
                    }
                }
                doc.close();
                in.close();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                    }
                }
                Message msg = new Message();
                msg.what = GET_UPDATE_VERSION_DATA;
                msg.arg1 = 1;
                handler.sendMessage(msg);
            }
        }
    }

    private void showDialogNew() {
        dismissProgressDialog();
        send = false;
        if (mCamera != null) {
            mCamera.unregisterIOSessionListener(this);
        }
        new AlertDialog.Builder(DeviceInfoActivity.this).setIcon(android.R.drawable.ic_dialog_alert).setTitle(getText(R.string.tips_warning)).setMessage(getText(R.string.tip_system_update_new)).setPositiveButton(getText(R.string.btn_ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        }).show();
    }

    private void dismissProgressDialog() {
        if (progressDialog != null) {
            progressDialog.cancel();
        }
        progressDialog = null;
    }


    private void showDialogOld() {
        dismissProgressDialog();
        new AlertDialog.Builder(DeviceInfoActivity.this).setIcon(android.R.drawable.ic_dialog_alert).setTitle(getText(R.string.tips_warning)).setMessage(getText(R.string.tip_system_update_old)).setPositiveButton(getText(R.string.btn_ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                if (System.currentTimeMillis() - updateTime <= 180000) return;

                // String dl = updateInfo.url+updateInfo.ver+".exe";
                String dl = redirectAddr;
                byte[] byt = new byte[128];
                byte[] bSvr = dl.getBytes();
                // Arrays.fill(byt, (byte)0);
                int len = bSvr.length > 128 ? 128 : bSvr.length;
                System.arraycopy(bSvr, 0, byt, 0, len);
                HiLog.v("dl:" + dl);
                updateTime = System.currentTimeMillis();
                send = true;
                //111
                if (mCamera != null) {
                    mCamera.registerIOSessionListener(DeviceInfoActivity.this);
                }
                showjuHuaDialog();
                mCamera.setReconnectTimes(20);
                mCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_DOWNLOAD, HiChipDefines.HI_P2P_S_SET_DOWNLOAD.parseContent(0, byt));

                new AlertDialog.Builder(DeviceInfoActivity.this).setIcon(android.R.drawable.ic_dialog_alert).setTitle(getText(R.string.tips_warning)).setMessage(getText(R.string.tip_system_update)).setPositiveButton(getText(R.string.btn_ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }).show();

            }
        }).setNegativeButton(getText(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        }).show();
    }


}
